package com.dabai.sas.activitys;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dabai.sas.R;
import com.dabai.sas.utils.AssetsUtils;
import com.dabai.sas.utils.DabaiUtils;

import com.dabai.sas.utils.DebugUtils;

import com.dabai.utils.DateUtils;
import com.dabai.utils.DownloadUtils;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.File;

import static android.os.Environment.DIRECTORY_PICTURES;


public class BrowserActivity extends AppCompatActivity {

    Context context;
    String TAG = "DABAI";
    WebView webView;
    private RefreshLayout refreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);

        context = getApplicationContext();

        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DabaiUtils.showToast(context, "请点击申请'储存权限'!");
            startActivity(new Intent(this, PermissionsActivity.class));
            finish();
            return;
        }

        webView = findViewById(R.id.webView);

        /*
          手势初始化
         */
        gesturesToInitialize();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //dark
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);


        try {
            webInit();
        } catch (Exception e) {
            new DebugUtils(this).showErrorMessage("初始化异常:\n" + e);
        }

    }

    //手势
    private void gesturesToInitialize() {
        //下拉
        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(refreshlayout -> webView.loadUrl(webView.getUrl()));
        refreshLayout.setRefreshHeader(new BezierRadarHeader(this));
        refreshLayout.setPrimaryColorsId(android.R.color.white, R.color.purple_500);
    }


    /**
     * web 初始化
     *
     * @throws Exception
     */
    private void webInit() throws Exception {

        Uri uri = getIntent().getData();

        if (uri == null) {
            //直接打开
            webView.loadUrl("file:///android_asset/homepage.html");
        } else {
            //其他应用打开
            String link = uri.toString();
            webView.loadUrl(link);
        }


        /**
         * 声明WebSettings子类
         */
        WebSettings webSettings = webView.getSettings();
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);


        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        }


        webView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
            String fileName = URLUtil.guessFileName(url, contentDisposition, mimeType);
            new MaterialDialog.Builder(this)
                    .title("下载内容").content(url)
                    .inputRangeRes(1, 100, R.color.purple_700)
                    .inputType(InputType.TYPE_CLASS_TEXT)
                    .input("文件名", fileName, (dialog, input) -> {

                    })
                    .positiveText("允许下载")
                    .onPositive((dialog, which) -> {
                        try {
                            assert dialog.getInputEditText() != null;
                            DabaiUtils.downloadBySystem(context, dialog.getInputEditText().getText().toString(), url, contentDisposition, mimeType);
                        } catch (Exception e) {
                            DabaiUtils.showToast(context, "调用系统下载管理器失败!");
                        }
                    })
                    .neutralText("取消")
                    .show();

        });

        /*
          WebViewClient
         */
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);

                //加载作用域...
                JSONArray jsonArray = JSONArray.parseArray(AssetsUtils.loadAssetsText(context, "jsscope/JsScope.json"));
                for (Object object : jsonArray.toArray()) {
                    JSONObject jsonObject = (JSONObject) object;
                    String jUrl = (String) jsonObject.get("url");
                    JSONArray jsScopes = (JSONArray) jsonObject.get("js_list");

                    //加载全局脚本
                    if (jUrl.equals("*")) {
                        for (Object object2 : jsScopes.toArray()) {
                            JSONObject jlObject = (JSONObject) object2;
                            AssetsUtils.loadJS(view, jlObject.getString("url"));
                            Log.d(TAG, "webView js脚本加载(全局): " + jlObject.getString("url"));
                        }
                        //加载 作用于url的脚本
                    } else if (url.contains(jUrl)) {
                        for (Object object2 : jsScopes.toArray()) {
                            JSONObject jlObject = (JSONObject) object2;
                            AssetsUtils.loadJS(view, jlObject.getString("url"));
                            Log.d(TAG, "webView js脚本加载(" + jlObject.getString("name") + "): " + jlObject.getString("url"));
                        }
                    }
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                super.shouldOverrideUrlLoading(view, url);

                //post提交
                postInit(url);

                if (url.startsWith("http:") || url.startsWith("https:") ||
                        url.startsWith("file:") || url.startsWith("content:")) {
                    view.loadUrl(url);
                } else {

                    //拦截百度Scheme
                    String scheme = Uri.parse(url).getScheme();
                    if (scheme.equals("baiduboxapp")||scheme.equals("baiduboxlite")){
                        return true;
                    }

                    new MaterialDialog.Builder(BrowserActivity.this)
                            .title("提示")
                            .content("是否允许使用第三方应用打开[" + scheme + "]协议?")
                            .positiveText("允许")
                            .onPositive((dialog, which) -> {
                                try {
                                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                    startActivity(intent);
                                } catch (Exception e) {
                                    DabaiUtils.showToast(context, "第三方应用打开失败!");
                                }
                            })
                            .negativeText("取消")
                            .show();

                    return true;
                }

                return false;//返回false 意思是不拦截，让webview自己处理
            }

        });

        /*
          WebChromeClient
         */
        webView.setWebChromeClient(new WebChromeClient() {

            // For Android  >= 5.0
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                BrowserActivity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }


            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (newProgress == 100) {
                    String title = view.getTitle();
                    if (!TextUtils.isEmpty(title)) {
                        refreshLayout.finishRefresh();
                        getSupportActionBar().setTitle(title);
                    }
                } else {
                    getSupportActionBar().setTitle(newProgress + "%");
                }
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(BrowserActivity.this);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm());
                b.setCancelable(false);
                b.create().show();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }
        });

            /*
        注册长按事件
         */
        onWebViewLongClickReg();

    }


    private void onWebViewLongClickReg() {

        webView.setOnLongClickListener(view -> {
            WebView.HitTestResult result = webView.getHitTestResult();
            if (null == result)
                return false;
            int type = result.getType();
            switch (type) {
                case WebView.HitTestResult.EDIT_TEXT_TYPE: // 选中的文字类型
                    break;
                case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
                    break;
                case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
                    break;
                case WebView.HitTestResult.GEO_TYPE: // 　地图类型
                    break;
                case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
                    break;
                case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: // 带有链接的图片类型
                case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项
                    String url = result.getExtra();

                    new MaterialDialog.Builder(BrowserActivity.this)
                            .title("保存图片")
                            .content(url)
                            .positiveText("保存到相册")
                            .onPositive((dialog, which) -> {
                                DownloadUtils.downloadFile(url, Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "/SAS/" + DateUtils.getNowTime(3) + ".jpg", new DownloadUtils.DownloadListener() {
                                    @Override
                                    public void onResult(String state, String filePath, File tagFile) {
                                        if (tagFile.exists()) {
                                            // 最后通知图库更新
                                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                                    Uri.fromFile(tagFile)));

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    DabaiUtils.showToast(BrowserActivity.this, "保存成功!");
                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    public void onProgress(String progress, long downed, long length) {

                                    }
                                });
                            })
                            .neutralText("取消")
                            .show();

            }
            return true;
        });

    }

    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    //文件选择
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "上传文件"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //上传文件
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                if (null != uploadFile) {
                    Uri result = data == null ? null
                            : data.getData();
                    uploadFile.onReceiveValue(result);
                    uploadFile = null;
                }
                if (null != uploadFiles) {
                    Uri result = data == null ? null
                            : data.getData();
                    uploadFiles.onReceiveValue(new Uri[]{result});
                    uploadFiles = null;
                }
            } else if (resultCode == RESULT_CANCELED) {
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(null);
                    uploadFile = null;
                }
            }
        }
    }


    /**
     * post 信息 判断提交
     */
    public void postInit(String link) {
        /**
         * 如果是 兔小巢 就 把机型信息提交
         */

        if (link.startsWith("https://support.qq.com/")) {

            String headLink = "https://txc.qq.com/static/desktop/img/products/def-product-logo.png";
            String postData = "nickname=" + DabaiUtils.getDeviceName(this) +
                    "&avatar=" + headLink +
                    "&openid=" + DabaiUtils.getDeviceID(this);

            webView.postUrl(link, postData.getBytes());
            refreshLayout.setEnableRefresh(false);
            Log.d(TAG, "兔小巢社区登录(+"+DabaiUtils.getDeviceName(this)+"+): 禁用下拉,传递登录态");

            // getSupportActionBar().setSubtitle("社区用户:" + DabaiUtils.getDeviceName(this));
        }else {
            refreshLayout.setEnableRefresh(true);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.refresh:
                webView.loadUrl(webView.getUrl());
                return true;
            case R.id.share:
                new DabaiUtils().sendText(this, webView.getTitle() + "\n" + webView.getUrl());
                return true;
            case R.id.copy_address:
                DabaiUtils.copyText(context, "" + webView.getUrl());
                return true;
            case R.id.using_other_open:
                new DabaiUtils().openLink(context, webView.getUrl());
                return true;
            case R.id.web_page_back:
                if (webView.canGoBack()) webView.goBack();
                return true;
            case R.id.web_page_forward:
                if (webView.canGoForward()) webView.goForward();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.html_viewer_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }


    //退出时的时间
    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();//返回上个页面
            return true;
        } else {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(context, "再按一次退出!", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return false;
        }

    }

}